import { Table, Tag, Typography, Card, Progress, Select, Space, Row, Col, Statistic, Tooltip, Button, Modal, Form, Collapse, message, Input, Popover, Switch } from '@/utils/antd-imports';
import { CheckOutlined, CloseOutlined, UserOutlined, ClockCircleOutlined, ExceptionOutlined, EditOutlined, PlusOutlined, MinusOutlined, ExportOutlined, DeleteOutlined, UnorderedListOutlined, TableOutlined } from '@/utils/icons';
import React, { useState, useRef } from 'react';














import InputNumber from 'antd/es/input-number';

import DatePicker from 'antd/es/date-picker';




import { Column } from '@ant-design/charts';

import dayjs from 'dayjs';
import * as XLSX from 'xlsx';

const { Title, Text } = Typography;
const { Panel } = Collapse;
const { Option } = Select;

// 生成员工编号
const generateEmployeeId = (index) => {
  return `EMP${String(index + 1).padStart(4, '0')}`;
};

// 生成入职时间 (随机生成2018-2023年间的日期)
const generateHireDate = () => {
  const year = 2018 + Math.floor(Math.random() * 6);
  const month = Math.floor(Math.random() * 12);
  const day = Math.floor(Math.random() * 28) + 1;
  return dayjs(`${year}-${month + 1}-${day}`).format('YYYY-MM-DD');
};

// 根据图片中的员工名单创建模拟数据
const generateAttendanceData = () => {
  const employeeNames = [
    '陈佳健', '常俊', '陈艳萍', '王红', '李明', 
    '刘粉', '张艳', '王丽萍', '刘燕', '王艳丽',
    '李春花', '王艳', '张艳', '李燕', '王艳萍'
  ];

  // 去重
  const uniqueNames = [...new Set(employeeNames)];
  
  const positions = ['前端工程师', '后端工程师', 'UI设计师', '测试工程师', '产品经理'];
  const departments = ['研发部', '设计部', '质量部', '产品部', '行政部'];
  
  return uniqueNames.map((name, index) => {
    const totalDays = 30; // 9月份有30天
    const presentDays = Math.floor(Math.random() * 5) + 25; // 出勤25-30天
    const lateHours = Math.floor(Math.random() * 5); // 迟到0-5小时
    const leaveEarlyHours = Math.floor(Math.random() * 3); // 早退0-3小时
    const leaveHours = Math.floor(Math.random() * 8); // 请假0-8小时
    const adjustHours = Math.floor(Math.random() * 4); // 调休0-4小时
    const annualLeaveHours = Math.floor(Math.random() * 16); // 年假0-16小时
    const maternityLeaveHours = Math.floor(Math.random() * 24); // 产假0-24小时
    const marriageLeaveHours = Math.floor(Math.random() * 8); // 婚假0-8小时
    const standbyHours = Math.floor(Math.random() * 4); // 待岗0-4小时
    const paternityLeaveHours = Math.floor(Math.random() * 8); // 陪产假0-8小时
    const weekdayOvertime = Math.floor(Math.random() * 10); // 工作日加班0-10小时
    const weekendOvertime = Math.floor(Math.random() * 8); // 周末加班0-8小时
    const holidayOvertime = Math.floor(Math.random() * 12); // 节假日加班0-12小时
    
    // 生成每日考勤记录
    const dailyRecords = [];
    for (let day = 1; day <= totalDays; day++) {
      const date = new Date(2024, 8, day); // 2024年9月
      const isWeekend = date.getDay() === 0 || date.getDay() === 6; // 准确判断周末
      
      let workHours = isWeekend ? 0 : 8; // 周末不计工作时间
      let overtimeHours = 0;
      
      // 随机生成加班
      if (!isWeekend && Math.random() > 0.7) {
        overtimeHours = Math.floor(Math.random() * 3) + 1;
      }
      
      dailyRecords.push({
        day,
        date: `9月${day}日`,
        workHours,
        overtimeHours,
        isWeekend,
        deductions: {
          late: 0,
          leaveEarly: 0,
          leave: 0,
          adjust: 0,
          annualLeave: 0,
          maternityLeave: 0,
          marriageLeave: 0,
          standby: 0,
          paternityLeave: 0,
          weekdayOvertime: isWeekend ? 0 : overtimeHours,
          weekendOvertime: isWeekend ? overtimeHours : 0
        }
      });
    }
    
    return {
      id: generateEmployeeId(index),
      name: name,
      position: positions[index % positions.length],
      department: departments[index % departments.length],
      hireDate: generateHireDate(),
      attendance: {
        present: presentDays * 8, // 打卡小时数
        late: lateHours,
        leaveEarly: leaveEarlyHours,
        leave: leaveHours,
        adjust: adjustHours,
        annualLeave: annualLeaveHours,
        maternityLeave: maternityLeaveHours,
        marriageLeave: marriageLeaveHours,
        standby: standbyHours,
        paternityLeave: paternityLeaveHours,
        weekdayOvertime: weekdayOvertime,
        weekendOvertime: weekendOvertime,
        holidayOvertime: holidayOvertime
      },
      dailyRecords
    };
  });
};

const AttendanceTable = () => {
  const [selectedMonth, setSelectedMonth] = useState(8); // 9月
  const [selectedYear, setSelectedYear] = useState(2024);
  const [showDetailView, setShowDetailView] = useState(false);
  const [selectedDay, setSelectedDay] = useState(null);
  const [editingWork, setEditingWork] = useState(false);
  const [editingOvertime, setEditingOvertime] = useState(false);
  const [form] = Form.useForm();
  const [deductionForm] = Form.useForm();
  const [deductionRecords, setDeductionRecords] = useState([]);
  const [activePopover, setActivePopover] = useState(null);
  const [selectedDate, setSelectedDate] = useState(null);
  const [showClearButton, setShowClearButton] = useState(false);
  const [attendanceData, setAttendanceData] = useState(generateAttendanceData());
  const totalWorkHours = 30 * 8; // 9月份应出勤小时数 (30天*8小时)

  // 计算考勤统计
  const calculateAttendanceStats = () => {
    return attendanceData.map(person => {
      const actualWorkHours = person.attendance.present - 
        person.attendance.late - 
        person.attendance.leaveEarly - 
        person.attendance.leave -
        person.attendance.adjust -
        person.attendance.annualLeave -
        person.attendance.maternityLeave -
        person.attendance.marriageLeave -
        person.attendance.standby -
        person.attendance.paternityLeave;
      
      const attendanceRate = (actualWorkHours / totalWorkHours) * 100;
      
      return {
        ...person,
        fullAttendance: totalWorkHours,
        actualWorkHours,
        attendanceRate: attendanceRate.toFixed(1),
        totalWorkHours
      };
    });
  };

  const attendanceStats = calculateAttendanceStats();

  // 总体统计
  const overallStats = {
    totalEmployees: attendanceData.length,
    avgAttendanceRate: (attendanceStats.reduce((sum, person) => sum + parseFloat(person.attendanceRate), 0) / attendanceStats.length).toFixed(1),
    totalWorkHours: attendanceStats.reduce((sum, person) => sum + person.actualWorkHours, 0),
    totalOvertime: attendanceStats.reduce((sum, person) => sum + person.attendance.weekdayOvertime + person.attendance.weekendOvertime, 0),
    totalLeave: attendanceStats.reduce((sum, person) => sum + person.attendance.leave, 0)
  };

  // 考勤柱状图配置
  const attendanceChartConfig = {
    data: attendanceStats,
    xField: 'name',
    yField: 'attendanceRate',
    label: {
      position: 'middle',
      style: {
        fill: '#FFFFFF',
        opacity: 0.6,
      },
      formatter: (text, item) => `${item.attendanceRate}%`,
    },
    xAxis: {
      label: {
        autoRotate: false,
      },
    },
    slider: {
      start: 0,
      end: 1,
    },
  };

  // 考勤明细表格列定义
  const attendanceColumns = [
    {
      title: '员工编号',
      dataIndex: 'id',
      key: 'id',
      width: 100,
      fixed: 'left'
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      fixed: 'left',
      render: (text, record) => (
        <div>
          <UserOutlined style={{ marginRight: 8, color: '#1890ff' }} />
          <Text strong>{text}</Text>
        </div>
      )
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 100
    },
    {
      title: '入职时间',
      dataIndex: 'hireDate',
      key: 'hireDate',
      width: 120,
      render: (date) => dayjs(date).format('YYYY-MM-DD')
    },
    {
      title: '满勤/应出勤',
      key: 'fullAttendance',
      width: 120,
      render: (_, record) => (
        <div>
          <Text strong style={{ fontSize: '16px' }}>{record.actualWorkHours}</Text>
          <Text type="secondary">/{record.fullAttendance}小时</Text>
          <Progress 
            percent={Math.round((record.actualWorkHours / record.fullAttendance) * 100)} 
            size="small" 
            strokeColor="#52c41a"
            showInfo={false}
          />
        </div>
      )
    },
    {
      title: '打卡',
      dataIndex: ['attendance', 'present'],
      key: 'present',
      width: 80,
      render: (text) => `${text}小时`
    },
    {
      title: '迟到',
      dataIndex: ['attendance', 'late'],
      key: 'late',
      width: 80,
      render: (text) => (
        <Tag color="orange" icon={<ClockCircleOutlined />}>
          {text}小时
        </Tag>
      )
    },
    {
      title: '早退',
      dataIndex: ['attendance', 'leaveEarly'],
      key: 'leaveEarly',
      width: 80,
      render: (text) => (
        <Tag color="orange" icon={<ClockCircleOutlined />}>
          {text}小时
        </Tag>
      )
    },
    {
      title: '工作日加班',
      dataIndex: ['attendance', 'weekdayOvertime'],
      key: 'weekdayOvertime',
      width: 100,
      render: (text) => (
        <Tag color="orange">
          {text}小时
        </Tag>
      )
    },
    {
      title: '周末加班',
      dataIndex: ['attendance', 'weekendOvertime'],
      key: 'weekendOvertime',
      width: 100,
      render: (text) => (
        <Tag color="red">
          {text}小时
        </Tag>
      )
    },
    {
      title: '节假日加班',
      dataIndex: ['attendance', 'holidayOvertime'],
      key: 'holidayOvertime',
      width: 100,
      render: (text) => (
        <Tag color="purple">
          {text}小时
        </Tag>
      )
    },
    {
      title: '请假',
      dataIndex: ['attendance', 'leave'],
      key: 'leave',
      width: 80,
      render: (text) => (
        <Tag color="purple" icon={<ExceptionOutlined />}>
          {text}小时
        </Tag>
      )
    },
    {
      title: '调休',
      dataIndex: ['attendance', 'adjust'],
      key: 'adjust',
      width: 80,
      render: (text) => `${text}小时`
    },
    {
      title: '年假',
      dataIndex: ['attendance', 'annualLeave'],
      key: 'annualLeave',
      width: 80,
      render: (text) => `${text}小时`
    },
    {
      title: '产假',
      dataIndex: ['attendance', 'maternityLeave'],
      key: 'maternityLeave',
      width: 80,
      render: (text) => `${text}小时`
    },
    {
      title: '婚假',
      dataIndex: ['attendance', 'marriageLeave'],
      key: 'marriageLeave',
      width: 80,
      render: (text) => `${text}小时`
    },
    {
      title: '待岗',
      dataIndex: ['attendance', 'standby'],
      key: 'standby',
      width: 80,
      render: (text) => `${text}小时`
    },
    {
      title: '陪产假',
      dataIndex: ['attendance', 'paternityLeave'],
      key: 'paternityLeave',
      width: 80,
      render: (text) => `${text}小时`
    },
    {
      title: '出勤率',
      dataIndex: 'attendanceRate',
      key: 'attendanceRate',
      width: 120,
      sorter: (a, b) => parseFloat(a.attendanceRate) - parseFloat(b.attendanceRate),
      render: (text) => (
        <Progress 
          percent={parseFloat(text)} 
          size="small"
          status={parseFloat(text) >= 95 ? 'success' : parseFloat(text) >= 90 ? 'normal' : 'exception'}
          format={percent => `${percent}%`}
        />
      )
    }
  ];

  // 月份选择器选项
  const monthOptions = [
    { label: '9月', value: 8 },
    { label: '10月', value: 9 },
    { label: '11月', value: 10 },
    { label: '12月', value: 11 }
  ];

  // 扣减项类型选项
  const deductionOptions = [
    { label: '迟到', value: 'late' },
    { label: '早退', value: 'leaveEarly' },
    { label: '工作日加班', value: 'weekdayOvertime' },
    { label: '周末加班', value: 'weekendOvertime' },
    { label: '节假日加班', value: 'holidayOvertime' },
    { label: '请假', value: 'leave' },
    { label: '调休', value: 'adjust' },
    { label: '年假', value: 'annualLeave' },
    { label: '产假', value: 'maternityLeave' },
    { label: '婚假', value: 'marriageLeave' },
    { label: '待岗', value: 'standby' },
    { label: '陪产假', value: 'paternityLeave' }
  ];

  // 处理工作时间点击
  const handleWorkClick = (dayRecord, employee, event) => {
    event.stopPropagation();
    
    const popoverKey = `work-${employee.id}-${dayRecord.day}`;
    if (activePopover === popoverKey) {
      setActivePopover(null);
      return;
    }
    
    setSelectedDay(dayRecord);
    setEditingWork(true);
    setEditingOvertime(false);
    setActivePopover(popoverKey);
    
    // 初始化扣减记录
    const records = [];
    for (const [key, value] of Object.entries(dayRecord.deductions)) {
      if (value > 0 && key !== 'weekdayOvertime' && key !== 'weekendOvertime') {
        records.push({
          id: Date.now() + Math.random(),
          type: key,
          hours: value
        });
      }
    }
    setDeductionRecords(records);
  };

  // 处理加班时间点击
  const handleOvertimeClick = (dayRecord, employee, event) => {
    event.stopPropagation();
    
    const popoverKey = `overtime-${employee.id}-${dayRecord.day}`;
    if (activePopover === popoverKey) {
      setActivePopover(null);
      return;
    }
    
    setSelectedDay(dayRecord);
    setEditingOvertime(true);
    setEditingWork(false);
    setActivePopover(popoverKey);
    form.setFieldsValue({
      weekdayOvertime: dayRecord.deductions.weekdayOvertime,
      weekendOvertime: dayRecord.deductions.weekendOvertime
    });
  };

  // 提交加班时间表单
  const handleOvertimeSubmit = (employee, dayRecord) => {
    form.validateFields().then(values => {
      const updatedDay = {
        ...dayRecord,
        overtimeHours: (values.weekdayOvertime || 0) + (values.weekendOvertime || 0),
        deductions: {
          ...dayRecord.deductions,
          weekdayOvertime: values.weekdayOvertime || 0,
          weekendOvertime: values.weekendOvertime || 0
        }
      };
      
      // 更新员工记录
      const updatedEmployee = {
        ...employee,
        dailyRecords: employee.dailyRecords.map(record => 
          record.day === dayRecord.day ? updatedDay : record
        )
      };
      
      // 更新数据
      const updatedData = attendanceData.map(emp => 
        emp.id === employee.id ? updatedEmployee : emp
      );
      
      setAttendanceData(updatedData);
      message.success('加班时间保存成功');
      setActivePopover(null);
    });
  };

  // 添加扣减记录
  const handleAddDeduction = () => {
    deductionForm.validateFields().then(values => {
      const newRecord = {
        id: Date.now(),
        type: values.type,
        hours: values.hours
      };
      setDeductionRecords([...deductionRecords, newRecord]);
      deductionForm.resetFields();
    });
  };

  // 删除扣减记录
  const handleDeleteDeduction = (id) => {
    setDeductionRecords(deductionRecords.filter(record => record.id !== id));
  };

  // 提交扣减记录
  const handleDeductionSubmit = (employee, dayRecord) => {
    const deductions = {};
    let totalDeduction = 0;
    
    deductionRecords.forEach(record => {
      deductions[record.type] = record.hours;
      totalDeduction += record.hours;
    });
    
    // 计算工作时间 = 8小时 - 扣减总时长
    const workHours = Math.max(0, 8 - totalDeduction);
    
    const updatedDay = {
      ...dayRecord,
      workHours,
      deductions: {
        ...dayRecord.deductions,
        ...deductions
      }
    };
    
    // 更新员工记录
    const updatedEmployee = {
      ...employee,
      dailyRecords: employee.dailyRecords.map(record => 
        record.day === dayRecord.day ? updatedDay : record
      )
    };
    
    // 更新数据
    const updatedData = attendanceData.map(emp => 
      emp.id === employee.id ? updatedEmployee : emp
    );
    
    setAttendanceData(updatedData);
    message.success('扣减记录保存成功，工作时间已自动计算');
    setActivePopover(null);
  };

  // 生成详情表格列
  const generateDetailColumns = () => {
    const columns = [
      {
        title: '员工',
        dataIndex: 'name',
        key: 'name',
        width: 100,
        fixed: 'left',
        render: (text) => <Text strong>{text}</Text>
      }
    ];
    
    // 添加日期列
    for (let day = 1; day <= 30; day++) {
      columns.push({
        title: (
          <div 
            style={{ 
              cursor: 'pointer',
              backgroundColor: selectedDate === day ? '#e6f7ff' : 'transparent',
              padding: '4px 8px',
              borderRadius: 4,
              border: selectedDate === day ? '1px solid #1890ff' : '1px solid transparent'
            }}
            onClick={() => handleDateClick(day)}
          >
            {day}
          </div>
        ),
        key: `day${day}`,
        width: 60,
        render: (_, employee) => {
          const dayRecord = employee.dailyRecords.find(d => d.day === day);
          if (!dayRecord) return null;
          
          return (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {/* 工作时间 */}
              <Popover
                placement="bottom"
                content={
                  <div style={{ width: 500 }}>
                    <Form form={deductionForm} layout="horizontal">
                      <Space>
                        <Form.Item
                          name="type"
                          label="扣减类型"
                          rules={[{ required: true, message: '请选择扣减类型' }]}
                          style={{ marginBottom: 0 }}
                        >
                          <Select style={{ width: 120 }}>
                            {deductionOptions.map(option => (
                              <Option key={option.value} value={option.value}>
                                {option.label}
                              </Option>
                            ))}
                          </Select>
                        </Form.Item>
                        <Form.Item
                          name="hours"
                          label="扣减小时"
                          rules={[{ required: true, message: '请输入扣减小时数' }]}
                          style={{ marginBottom: 0 }}
                        >
                          <InputNumber min={0} max={8} />
                        </Form.Item>
                        <Form.Item style={{ marginBottom: 0 }}>
                          <Button 
                            type="primary" 
                            icon={<PlusOutlined />} 
                            onClick={handleAddDeduction}
                          >
                            添加
                          </Button>
                        </Form.Item>
                      </Space>
                    </Form>
                    
                    <div style={{ marginTop: 16 }}>
                      {deductionRecords.length > 0 ? (
                        <Table
                          dataSource={deductionRecords}
                          columns={[
                            {
                              title: '扣减类型',
                              dataIndex: 'type',
                              key: 'type',
                              render: (text) => deductionOptions.find(o => o.value === text)?.label
                            },
                            {
                              title: '扣减小时',
                              dataIndex: 'hours',
                              key: 'hours'
                            },
                            {
                              title: '操作',
                              key: 'action',
                              render: (_, record) => (
                                <Button 
                                  type="text" 
                                  danger 
                                  icon={<DeleteOutlined />} 
                                  onClick={() => handleDeleteDeduction(record.id)}
                                />
                              )
                            }
                          ]}
                          pagination={false}
                          size="small"
                        />
                      ) : (
                        <Text type="secondary">暂无扣减记录</Text>
                      )}
                    </div>
                    
                    <div style={{ marginTop: 16 }}>
                      <Text strong>工作时间计算公式：8小时 - 扣减总时长 = {Math.max(0, 8 - deductionRecords.reduce((sum, record) => sum + record.hours, 0))}小时</Text>
                    </div>
                    
                    {deductionRecords.length > 0 && (
                      <div style={{ marginTop: 16, textAlign: 'right' }}>
                        <Button type="primary" onClick={() => handleDeductionSubmit(employee, dayRecord)}>
                          保存扣减记录
                        </Button>
                      </div>
                    )}
                  </div>
                }
                title={`${employee.name} - ${dayRecord.date} 工作时间调整`}
                trigger="click"
                visible={activePopover === `work-${employee.id}-${dayRecord.day}`}
                onVisibleChange={(visible) => {
                  if (!visible) setActivePopover(null);
                }}
              >
                <div 
                  style={{ 
                    cursor: 'pointer', 
                    backgroundColor: activePopover === `work-${employee.id}-${dayRecord.day}` ? '#e6f7ff' : 'transparent',
                    padding: 4,
                    borderRadius: 4,
                    border: activePopover === `work-${employee.id}-${dayRecord.day}` ? '1px solid #1890ff' : '1px solid #f0f0f0',
                    textAlign: 'center'
                  }}
                  onClick={(e) => handleWorkClick(dayRecord, employee, e)}
                >
                  {dayRecord.isWeekend ? '-' : dayRecord.workHours}
                </div>
              </Popover>
              
              {/* 加班时间 */}
              <Popover
                placement="bottom"
                content={
                  <div style={{ width: 600, padding: '24px' }}>
                    <div style={{ marginBottom: '24px', textAlign: 'center' }}>
                      <Text strong style={{ fontSize: '18px', color: '#1890ff' }}>
                        {employee.name} - {dayRecord.date} 加班时间调整
                      </Text>
                    </div>
                    
                    <Form form={form} layout="vertical">
                      <Row gutter={[24, 16]}>
                        <Col span={8}>
                          <Form.Item 
                            name="weekdayOvertime" 
                            label={
                              <span style={{ fontSize: '14px', fontWeight: '500' }}>
                                工作日加班
                              </span>
                            }
                            extra={
                              <span style={{ fontSize: '12px', color: '#666' }}>
                                仅工作日可填写
                              </span>
                            }
                          >
                            <InputNumber 
                              min={0} 
                              max={12}
                              style={{ width: '100%', height: '40px' }} 
                              disabled={dayRecord.isWeekend}
                              placeholder="0"
                              addonAfter="小时"
                            />
                          </Form.Item>
                        </Col>
                        <Col span={8}>
                          <Form.Item 
                            name="weekendOvertime" 
                            label={
                              <span style={{ fontSize: '14px', fontWeight: '500' }}>
                                周末加班
                              </span>
                            }
                            extra={
                              <span style={{ fontSize: '12px', color: '#666' }}>
                                仅周末可填写
                              </span>
                            }
                          >
                            <InputNumber 
                              min={0} 
                              max={16}
                              style={{ width: '100%', height: '40px' }} 
                              disabled={!dayRecord.isWeekend}
                              placeholder="0"
                              addonAfter="小时"
                            />
                          </Form.Item>
                        </Col>
                        <Col span={8}>
                          <Form.Item 
                            name="holidayOvertime" 
                            label={
                              <span style={{ fontSize: '14px', fontWeight: '500' }}>
                                节假日加班
                              </span>
                            }
                            extra={
                              <span style={{ fontSize: '12px', color: '#666' }}>
                                节假日可填写
                              </span>
                            }
                          >
                            <InputNumber 
                              min={0} 
                              max={24}
                              style={{ width: '100%', height: '40px' }} 
                              placeholder="0"
                              addonAfter="小时"
                            />
                          </Form.Item>
                        </Col>
                      </Row>
                      
                      <div style={{ 
                        marginTop: '24px', 
                        marginBottom: '24px',
                        padding: '16px 20px', 
                        backgroundColor: '#f8f9fa', 
                        borderRadius: '8px',
                        border: '1px solid #e9ecef',
                        boxShadow: '0 2px 4px rgba(0,0,0,0.05)'
                      }}>
                        <div style={{ marginBottom: '8px' }}>
                          <Text type="secondary" style={{ fontSize: '13px', fontWeight: '500' }}>
                            当前状态: 
                            <Tag color={dayRecord.isWeekend ? 'blue' : 'green'} style={{ marginLeft: '8px' }}>
                              {dayRecord.isWeekend ? '周末' : '工作日'}
                            </Tag>
                          </Text>
                        </div>
                        <div>
                          <Text type="secondary" style={{ fontSize: '13px' }}>
                            建议加班时长: 
                            <Text style={{ color: '#1890ff', fontWeight: '500' }}>
                              {dayRecord.isWeekend ? '4-8小时' : '1-4小时'}
                            </Text>
                          </Text>
                        </div>
                      </div>
                      
                      <div style={{ 
                        marginTop: '24px', 
                        textAlign: 'right',
                        paddingTop: '16px',
                        borderTop: '1px solid #f0f0f0'
                      }}>
                        <Space size="middle">
                          <Button 
                            size="large"
                            onClick={() => setActivePopover(null)}
                            style={{ minWidth: '80px' }}
                          >
                            取消
                          </Button>
                          <Button 
                            type="primary" 
                            size="large"
                            onClick={() => handleOvertimeSubmit(employee, dayRecord)}
                            style={{ minWidth: '80px' }}
                          >
                            保存
                          </Button>
                        </Space>
                      </div>
                    </Form>
                  </div>
                }
                title={`${employee.name} - ${dayRecord.date} 加班时间调整`}
                trigger="click"
                visible={activePopover === `overtime-${employee.id}-${dayRecord.day}`}
                onVisibleChange={(visible) => {
                  if (!visible) setActivePopover(null);
                }}
              >
                <div 
                  style={{ 
                    cursor: 'pointer', 
                    backgroundColor: activePopover === `overtime-${employee.id}-${dayRecord.day}` ? '#e6f7ff' : 'transparent',
                    padding: 4,
                    borderRadius: 4,
                    color: '#fa8c16',
                    border: activePopover === `overtime-${employee.id}-${dayRecord.day}` ? '1px solid #1890ff' : '1px solid #f0f0f0',
                    textAlign: 'center'
                  }}
                  onClick={(e) => handleOvertimeClick(dayRecord, employee, e)}
                >
                  {dayRecord.overtimeHours > 0 ? dayRecord.overtimeHours : '-'}
                </div>
              </Popover>
            </div>
          );
        }
      });
    }
    
    return columns;
  };

  // 生成详情表格数据
  const generateDetailData = () => {
    return attendanceData;
  };

  // 导出Excel
  // 处理日期列点击
  const handleDateClick = (day) => {
    if (selectedDate === day) {
      // 如果点击的是已选中的日期，则取消选中
      setSelectedDate(null);
      setShowClearButton(false);
    } else {
      // 选中新的日期
      setSelectedDate(day);
      setShowClearButton(true);
    }
  };

  // 清除指定日期的数据
  const handleClearDate = () => {
    if (selectedDate) {
      // 更新数据，清除指定日期的所有记录
      const updatedData = attendanceData.map(employee => ({
        ...employee,
        dailyRecords: employee.dailyRecords.map(record => 
          record.day === selectedDate 
            ? {
                ...record,
                workHours: record.isWeekend ? 0 : 8, // 重置为默认值
                overtimeHours: 0, // 清除加班时间
                deductions: {
                  ...record.deductions,
                  weekdayOvertime: 0,
                  weekendOvertime: 0,
                  holidayOvertime: 0
                }
              }
            : record
        )
      }));
      
      setAttendanceData(updatedData);
      message.success(`已清除 ${selectedDate} 日的工作时间和加班时间数据`);
      setShowClearButton(false);
      setSelectedDate(null);
    }
  };

  // 导出Excel - 包含汇总视图和详情视图
  const handleExport = () => {
    // 创建工作簿
    const wb = XLSX.utils.book_new();
    
    // 汇总视图数据
    const summaryData = attendanceStats.map(person => ({
      '员工编号': person.id,
      '姓名': person.name,
      '部门': person.department,
      '入职时间': person.hireDate,
      '满勤/应出勤': `${person.actualWorkHours}/${person.fullAttendance}小时`,
      '打卡': `${person.attendance.present}小时`,
      '迟到': `${person.attendance.late}小时`,
      '早退': `${person.attendance.leaveEarly}小时`,
      '请假': `${person.attendance.leave}小时`,
      '调休': `${person.attendance.adjust}小时`,
      '年假': `${person.attendance.annualLeave}小时`,
      '产假': `${person.attendance.maternityLeave}小时`,
      '婚假': `${person.attendance.marriageLeave}小时`,
      '待岗': `${person.attendance.standby}小时`,
      '陪产假': `${person.attendance.paternityLeave}小时`,
      '工作日加班': `${person.attendance.weekdayOvertime}小时`,
      '周末加班': `${person.attendance.weekendOvertime}小时`,
      '出勤率': `${person.attendanceRate}%`
    }));

    // 详情视图数据
    const detailData = [];
    attendanceData.forEach(employee => {
      // 工作时间行
      const workRow = {
        '员工': employee.name,
        '类型': '工作时间'
      };
      for (let day = 1; day <= 30; day++) {
        const dayRecord = employee.dailyRecords.find(d => d.day === day);
        workRow[`${day}日`] = dayRecord ? (dayRecord.isWeekend ? '' : dayRecord.workHours) : '';
      }
      detailData.push(workRow);
      
      // 加班时间行
      const overtimeRow = {
        '员工': employee.name,
        '类型': '加班时间'
      };
      for (let day = 1; day <= 30; day++) {
        const dayRecord = employee.dailyRecords.find(d => d.day === day);
        let value = '';
        if (dayRecord) {
          if (dayRecord.isWeekend) {
            value = dayRecord.overtimeHours > 0 ? dayRecord.overtimeHours : '';
          } else {
            value = dayRecord.overtimeHours > 0 ? dayRecord.overtimeHours : '0';
          }
        }
        overtimeRow[`${day}日`] = value;
      }
      detailData.push(overtimeRow);
    });

    // 创建汇总视图工作表
    const summaryWS = XLSX.utils.json_to_sheet(summaryData);
    XLSX.utils.book_append_sheet(wb, summaryWS, '汇总视图');

    // 创建详情视图工作表
    const detailWS = XLSX.utils.json_to_sheet(detailData);
    XLSX.utils.book_append_sheet(wb, detailWS, '详情视图');

    // 导出文件
    XLSX.writeFile(wb, `全体员工考勤表_${selectedYear}年${selectedMonth + 1}月.xlsx`);
    message.success('Excel文件导出成功！');
  };
  return (
    <div style={{ padding: 24, background: '#f0f2f5', minHeight: '100vh' }}>
      {/* 头部标题和筛选 */}
      <div style={{ marginBottom: 16 }}>
        <Row justify="space-between" align="middle">
          <Col>
            <Space>
              <Select 
                value={selectedMonth}
                onChange={setSelectedMonth}
                options={monthOptions}
                style={{ width: 100 }}
              />
              <Select 
                value={selectedYear}
                onChange={setSelectedYear}
                options={[{ label: '2024年', value: 2024 }]}
                style={{ width: 120 }}
              />
            </Space>
          </Col>
        </Row>
      </div>

      {/* 总体统计 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总员工数"
              value={overallStats.totalEmployees}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均出勤率"
              value={overallStats.avgAttendanceRate}
              suffix="%"
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总正常工时"
              value={overallStats.totalWorkHours}
              suffix="小时"
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总加班工时"
              value={overallStats.totalOvertime}
              suffix="小时"
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 考勤统计图表 */}
      <Card 
        title="员工出勤率统计" 
        style={{ marginBottom: 16 }}
        extra={<Text type="secondary">数据更新至: 2024-09-30</Text>}
      >
        <Column {...attendanceChartConfig} height={300} />
      </Card>

      {/* 考勤明细表格 */}
      <Card 
        title={
          <Space>
            {showDetailView ? '员工考勤详情表' : '员工考勤明细表'}
            <Button 
              type="text" 
              icon={showDetailView ? <TableOutlined /> : <UnorderedListOutlined />}
              onClick={() => setShowDetailView(!showDetailView)}
            >
              {showDetailView ? '切换为汇总视图' : '切换为详情视图'}
            </Button>
          </Space>
        }
        extra={
          <Space>
            <Button 
              icon={<ExportOutlined />} 
              onClick={handleExport}
            >
              导出Excel
            </Button>
            {selectedDate && (
              <Button 
                danger
                onClick={handleClearDate}
              >
                清除{selectedDate}日数据
              </Button>
            )}
            <Button 
              type="primary"
              onClick={() => {
                message.success('考勤数据提交成功！');
              }}
            >
              提交
            </Button>
            <Text type="secondary">统计周期: 2024-09-01 至 2024-09-30</Text>
          </Space>
        }
      >
        {showDetailView ? (
          <Table
            columns={generateDetailColumns()}
            dataSource={generateDetailData()}
            rowKey="id"
            pagination={{ 
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
            }}
            scroll={{ x: 2000 }}
            bordered
            size="small"
          />
        ) : (
          <Table
            columns={attendanceColumns}
            dataSource={attendanceStats}
            rowKey="id"
            pagination={{ 
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
            }}
            scroll={{ x: 2200 }}
            bordered
            size="middle"
          />
        )}
      </Card>
    </div>
  );
};

export default AttendanceTable;